package world.criver.h50529.function;

import com.sun.jna.Native;
import com.sun.jna.Pointer;
import com.sun.jna.platform.win32.Kernel32;
import com.sun.jna.platform.win32.User32;
import com.sun.jna.platform.win32.WinDef;
import com.sun.jna.platform.win32.WinUser;
import world.criver.h50529.data.daControllers;
import world.criver.h50529.data.daData;
import world.criver.h50529.enums.enumKeyCode;

public class funHotkey {
    private WinUser.HHOOK hook;
    /**
     * 按键触发回调函数
     */
    private WinUser.LowLevelKeyboardProc keyboardProc=new WinUser.LowLevelKeyboardProc(){
        @Override
        public WinDef.LRESULT callback(int i, WinDef.WPARAM wparam, WinUser.KBDLLHOOKSTRUCT kb) {
            if(wparam.intValue()==WinUser.WM_KEYDOWN){
                for(enumKeyCode k:enumKeyCode.values()){
                    if(kb.vkCode==k.getId()){
                        daControllers.page1.listenKey(k.name().replaceAll("_",""));
                    }else if(kb.vkCode==163){
                        daControllers.page1.listenKey("Ctrl");
                        break;
                    }else if(kb.vkCode==160){
                        daControllers.page1.listenKey("Shift");
                        break;
                    }else if(kb.vkCode==165){
                        daControllers.page1.listenKey("Alt");
                        break;
                    }
                }
            }
            return User32.INSTANCE.CallNextHookEx(hook,i,wparam,new WinDef.LPARAM(Pointer.nativeValue(kb.getPointer())));
        }
    };

    /**
     * 添加钩子
     */
    public void addHook(){
        //模块句柄 null代表返回自身进程
        WinDef.HMODULE hmodule= Kernel32.INSTANCE.GetModuleHandle(null);
        //设置钩子 钩子类型,触发回调函数,所属进程,进程ID（0为全局钩子）
        hook=User32.INSTANCE.SetWindowsHookEx(WinUser.WH_KEYBOARD_LL,keyboardProc,hmodule,0);
        daControllers.page1.addTip("已启动监听.");
        Thread.startVirtualThread(() -> {
            while(daData.start_listen){
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                    throw new RuntimeException(e);
                }
            }
        });
    }

    /**
     * 移除钩子
     */
    public void removeHook(){
        User32.INSTANCE.UnhookWindowsHookEx(hook);
        daControllers.page1.addTip("已停止监听.");
    }
}
